#include "../include/ppm.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

Image* readppm(char *nom){
    FILE * fdat;
    int width, height, max_val;
    char P6[3];
    char temp;
    PixelsRGB* Source;
    char comment[200];
    int i;
    Image* image;
    
    fdat = fopen(nom,"r");
    if (!fdat){
        printf("\n !Probleme en lecture de %s ! \n",nom);
        exit(-1);
    }
    
    /* Recup de P6 */
    fread(P6,1,2,fdat);
    fread(&temp,1,1,fdat);
    i=0;
    while (temp == ' ' || temp == '\n' || temp == '#'){
        if (temp == '#'){ /* On est tombe sur un caractere */
            comment[i] = temp;
            i++;
            while(temp != '\n'){
                comment[i] = temp;
                i++;
                fread(&temp,1,1,fdat);
	        }	
        }
        fread(&temp,1,1,fdat);
    }
    /* Recup de la largeur */
    width = 0;
    while ((temp >= '0') && (temp <= '9')){
        width = width * 10;
        width += (temp - '0');
        fread(&temp,1,1,fdat);
    }
    /* Saute les blancs */
    while (temp == ' ' || temp == '\n' || temp == '#'){
        if (temp == '#'){
            while (temp != '\n'){
                fread(&temp,1,1,fdat);
            }
        }
        fread(&temp,1,1,fdat);
    }
    /* Recup de la hauteur */
    height = 0;
    while ((temp >= '0') && (temp <= '9')){
        height = height * 10;
        height += (temp - '0');
        fread(&temp,1,1,fdat);
    }
    /* Saute les blancs et autres */
    while (temp == ' ' || temp == '\n' || temp == '#'){
        if (temp == '#'){
            while (temp != '\n'){
                fread(&temp,1,1,fdat);
            }
        }
        fread(&temp,1,1,fdat);
    }
    /* Recup valeur max */
    max_val = 0;
    while ((temp >= '0') && (temp <= '9')){
        max_val = max_val * 10;
        max_val += (temp - '0');
        fread(&temp,1,1,fdat);
    }
    /* Lecture du tableau de pixels */
    Source = (PixelsRGB *) malloc(sizeof(PixelsRGB)*width*height);
    fread(Source, sizeof(PixelsRGB), width*height, fdat);
    
    fclose(fdat);
    
    image = (Image *)malloc(sizeof(Image));
    image->nbLines = height;
    image->nbColumns = width;
    image->maxVal = max_val;
    image->pixels = Source;
   
    return(image);
}

int writeppm(Image* image, char* nom){
    FILE * fdat;
    int taille;
    
    fdat = fopen(nom,"w");
    if (!fdat){
        printf("\n !Probleme en ecriture de %s ! \n",nom);
        exit(-1);
    }
    
    fprintf(fdat,"P6\n#Imac Tower Defense - 2013 - Angeline & Adrien\n%d %d\n%d\n",image->nbColumns,image->nbLines,image->maxVal);
    taille = fwrite(image->pixels, sizeof(PixelsRGB), image->nbColumns * image->nbLines, fdat);
    fclose(fdat);
    
    if (taille != image->nbColumns * image->nbLines){ //On vérifie que le fichier fait bien la taille qu'il devrait faire
       return 0; 
    } 
    return 1; // tout c'est bien passé !
}